import 'package:flutter/material.dart';
import '../services/auth_service.dart';
import '../models/user_model.dart';

class AuthProvider with ChangeNotifier {
  final AuthService _authService;
  User? _user;
  bool _isLoading = false;
  String _errorMessage = '';
  AuthProvider(this._authService);

  User? get user => _user;
  String get errorMessage => _errorMessage;
  bool get isLoading => _isLoading;

  Future<void> login(String email, String password) async {
    _isLoading = true;
    _errorMessage = '';
    notifyListeners();

    try {
      _user = await _authService.login(email, password);
      // 保存token到本地存储
    } catch (e) {
      rethrow;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> register(String email, String password, String username) async {
    _isLoading = true;
    notifyListeners();

    try {
      _user = await _authService.register(email, password, username);
    } catch (e) {
      _errorMessage = '登录失败: ${e.toString()}';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> fetchProfile() async {
    _isLoading = true;
    notifyListeners();

    try {
      _user = await _authService.getProfile();
    } catch (e) {
      _errorMessage = '注册失败: ${e.toString()}';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> logout() async {
    try {
      await _authService.logout();
      _user = null;
      // 清除本地token
      // await storage.delete('auth_token');
    } catch (e) {
      _errorMessage = '登出失败: ${e.toString()}';
      rethrow;
    } finally {
      notifyListeners();
    }
  }
}
